//
//  OtherViewController.m
//  BigToBig
//
//  Created by admin on 16/4/29.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "OtherViewController.h"
#import "PlayModel.h"
#import "PlayUserModel.h"
#import "PlayMoveViewController.h"
static int p = 0;
static int offset = 0;
static int each = 2;


@interface OtherViewController()<UITableViewDelegate,UITableViewDataSource>
{
    
//    UIButton *PlayBtn;
    UIView *lineView;
//    UIImageView *imageView;
//    UILabel *VMRnumberLb;
//    UILabel *titleLb;
//    UILabel *useCountLb;
//    UIImageView *PlayView;
}
@property (nonatomic ,weak)UITableView *OtherTab;
//@property (nonatomic ,strong)NSMutableArray *tableData/;
@property (nonatomic ,strong)NSMutableArray *OtherArray;
@property (nonatomic ,strong)NSMutableArray *UserModelArray;
@property (nonatomic ,weak)UIImageView *imageView;


@end
@implementation OtherViewController
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    NSMutableArray *OtherArray = [NSMutableArray array];
    self.OtherArray = OtherArray;
    
    //设置系统自带的tableview不能滚动
    UITableView *OtherTab = [[UITableView alloc]initWithFrame:CGRectMake(0, 100, kScreenWidth, kScreenHeight - 149)];
    self.OtherTab = OtherTab;
    self.OtherTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    OtherTab.delegate = self;
    OtherTab.dataSource = self;
    [self.view addSubview:OtherTab];
    
    self.OtherTab.showsVerticalScrollIndicator = NO;
    self.OtherTab.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loaddata1)];
    self.OtherTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    // 马上进入刷新状态
    [self.OtherTab.mj_header beginRefreshing];
//    [self.OtherTab.mj_footer beginRefreshing];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)loadData{
    
    
    [self.imageView removeFromSuperview];

//    Reachability *reach = [Reachability reachabilityForInternetConnection];
//    NetworkStatus status = [reach currentReachabilityStatus];
//    if (status == NotReachable) {
//        
//        
//        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
//        HUD.labelText = @"请检查网络连接";
//        HUD.mode = MBProgressHUDModeText;
//        [HUD hide:YES afterDelay:1.0];
//        [self.OtherTab.mj_header endRefreshing];
//        
//        UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
//        imageView.image = [UIImage imageNamed:@"not_data"];
//        self.imageView = imageView;
//        imageView.backgroundColor = [UIColor whiteColor];
//
//        imageView.contentMode = UIViewContentModeCenter;
//        [self.OtherTab addSubview:imageView];
//
//        return;
//        
//    }
    NSLog(@"%ld",self.OtherArray.count);
    offset = 0;
    
    [self.OtherArray removeAllObjects];

        NSString *count = [NSString stringWithFormat:@"%d",p * 2];
        NSLog(@"%@",count);
        NSDictionary *params = @{@"category":@"26",@"offset":@"0",@"each":@"2",@"site_id":@"0"};
        [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/live/search?" params:params success:^(id json) {
            
            NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            
            NSMutableArray *userModelArray = [NSMutableArray array];
            self.UserModelArray = userModelArray;
            NSMutableArray *OtherArray = dict[@"live"];
            
            NSLog(@"%ld",OtherArray.count);

            for (int i = 0; i < OtherArray.count; i++) {
                
                NSDictionary *dict = OtherArray[i];
                
                NSMutableDictionary *ObliveDict = dict[@"obj_live"];
                NSMutableDictionary *userDict = dict[@"user"];
                
                //字典转模型
                PlayModel *OtherMD = [PlayModel PlayModelWithDict:ObliveDict];
                
                PlayUserModel *OtherUserMD = [PlayUserModel PlayUserModelWithDict:userDict];
                
                [self.OtherArray addObject:OtherMD];
                
                [self.UserModelArray addObject:OtherUserMD];
                NSLog(@"%@",OtherMD.category);
                NSLog(@"%@",OtherArray);

                NSLog(@"%@",OtherUserMD.userid);
                
            }
            
            if (OtherArray.count == 0) {
            
                UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
                imageView.image = [UIImage imageNamed:@"not_data"];
                imageView.contentMode = UIViewContentModeCenter;
                imageView.backgroundColor = [UIColor whiteColor];

                self.imageView = imageView;
                [self.OtherTab addSubview:imageView];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.OtherTab reloadData];
                
            });
            p++;
//            [self.OtherTab.mj_footer endRefreshing];
            [self.OtherTab.mj_header endRefreshing];
            
        } failure:^(NSError *error) {
            
//            [self.OtherTab.mj_footer endRefreshing];
            [self.OtherTab.mj_header endRefreshing];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.OtherTab reloadData];

                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                HUD.labelText = @"网络请求失败";
                HUD.mode = MBProgressHUDModeText;
                [HUD hide:YES afterDelay:1.0];
                
                UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
                imageView.image = [UIImage imageNamed:@"not_data"];
                self.imageView = imageView;
                imageView.contentMode = UIViewContentModeCenter;
                imageView.backgroundColor = [UIColor whiteColor];
                [self.OtherTab addSubview:imageView];
                
            });
        }];
        
    
}

- (void)loaddata1{

    offset = offset + each;
    
    NSString *str = [NSString stringWithFormat:@"%d",offset];
    NSDictionary *params = @{@"category":@"26",@"offset":str,@"each":@"2",@"site_id":@"0"};
    
    [HttpTool postWithURL: @"http://61.135.176.43:6080/bigtobig/live/search?" params:params success:^(id json) {
        
        NSLog(@"%@",json);
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSMutableArray *JinRongArray = dict[@"live"];
        
        
        for (int i = 0; i < JinRongArray.count; i++) {
            
            
            NSDictionary *dict = JinRongArray[i];
            NSMutableDictionary *userDict = dict[@"user"];
            PlayUserModel *JinRongUserMD = [PlayUserModel PlayUserModelWithDict:userDict];
            
            NSMutableDictionary *ObliveDict = dict[@"obj_live"];
            PlayModel *JinRongMD = [PlayModel PlayModelWithDict:ObliveDict];
            
            //字典转模型
            [self.OtherArray addObject:JinRongMD];
            [self.UserModelArray addObject:JinRongUserMD];
            
            NSLog(@"%@",JinRongMD.category);
            NSLog(@"%@",JinRongUserMD.userid);
            
        }
        
        
//        if (self.OtherArray.count == 0) {
//            
//            UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
//            imageView.image = [UIImage imageNamed:@"not_data"];
//            [self.OtherTab addSubview:imageView];
//        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.OtherTab reloadData];
            
        });
        
        p++;
        
        [self.OtherTab.mj_footer endRefreshing];
//        [self.OtherTab.mj_header endRefreshing];
        
    } failure:^(NSError *error) {
        
        NSLog(@"%@",error.userInfo);
        [self.OtherTab reloadData];
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        HUD.labelText = @"网络请求失败";
        HUD.mode = MBProgressHUDModeText;
        [HUD hide:YES afterDelay:1.0];
        
//        UIImageView *noDataImage = [[UIImageView alloc]initWithFrame:self.OtherTab.bounds];
//        noDataImage.contentMode = UIViewContentModeCenter;
//        noDataImage.image = [UIImage imageNamed:@"not_data"];
//        noDataImage.backgroundColor = [UIColor whiteColor];
//
//        [self.OtherTab addSubview:noDataImage];
        
        [self.OtherTab.mj_footer endRefreshing];
//        [self.OtherTab.mj_header endRefreshing];
    }];
    
}
- (NSString *)md5HexDigest:(NSString*)password
{
    
    const char *original_str = [password UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    NSLog(@"Encryption Result = %@",mdfiveString);
    return mdfiveString;
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    

    return self.OtherArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //为了防止cell重用设置唯一的cellID
    NSString *cellID = [NSString stringWithFormat:@"Cell%ld%ld",(long)[indexPath section],(long)[indexPath row]];

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (cell==nil) {
        
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    
    }
  

    if (self.OtherArray.count>0) {
        
        PlayModel *OtherMD = self.OtherArray[indexPath.row];
        PlayUserModel *OtherUserMD = self.UserModelArray[indexPath.row];
        //设置cell上的label
       UILabel *titleLb = [[UILabel alloc]initWithFrame:CGRectMake(75, 17.5f, 100, 20)];
        titleLb.font = [UIFont systemFontOfSize:12.0];
        //        titleLb.text = @"创业生态园";
        titleLb.text = OtherMD.theme;
       UILabel *VMRnumberLb = [[UILabel alloc]initWithFrame:CGRectMake(75, 37.5, 100, 20)];
        //    VMRnumberLb.text = Vm.conference_name;
        VMRnumberLb.text = @"路演项目";
        VMRnumberLb.font = [UIFont systemFontOfSize:12.0];
        
       UILabel *useCountLb = [[UILabel alloc]initWithFrame:CGRectMake(230, 15.0f, 100, 30)];
        useCountLb.font = [UIFont systemFontOfSize:12.0];
        
        NSDictionary *params = @{@"activityId":OtherMD.active_id};
        [HttpTool postWithURL:@"http://sdk2.karat.tv:8081/activity/onlineVeiwers?" params:params success:^(id json) {
            
            NSString *str = json[@"payload"];
            NSLog(@"%@",str);
            NSString *pepoleCountStr = [NSString stringWithFormat:@" %@人在线",str];
            useCountLb.text = pepoleCountStr;
            
        } failure:^(NSError *error) {
            
            
        }];

        //设置头像图片
      UIImageView *imageView =[[UIImageView alloc]init];
//        [imageView setImage:[UIImage imageNamed:@"tx"]];
        imageView.frame = CGRectMake(15.0f,7, 45, 45);
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 27;
        
        
        NSString *uidStr = [NSString stringWithFormat:@"%@",OtherUserMD.userid];
        
        NSString *str1 = [self md5HexDigest:uidStr];
        
        NSString *b = [str1 substringWithRange:NSMakeRange(8,16)];
        NSString *str2 = @".png";
        NSString *imgName = [NSString stringWithFormat:@"%@%@",b,str2];
        NSLog(@"%@",imgName);
        NSString *HeadImageUrl = [NSString stringWithFormat:@"http://172.16.52.24:8030/data/HeadPortrait/%@",imgName];
        
        NSLog(@"%@",HeadImageUrl);
        
        //        NSLog(@"%@",JinRongMD.front_cover);
        
        UIImageView *imageView1 = [[UIImageView alloc]init];
        
        [imageView1 sd_setImageWithURL:[NSURL URLWithString:HeadImageUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            //设置头像图片
            if (error) {
                
                [imageView setImage:[UIImage imageNamed:@"tx"]];
                
                return ;
            }
            imageView.image = imageView1.image;
            
            
        }];
        

       UIButton *PlayBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 61, kScreenWidth, 180)];
        PlayBtn.tag = indexPath.row;

        NSString *str = [NSString stringWithFormat:@"http://61.135.176.43:6080/data/FrontCover/%@",OtherMD.front_cover];
        NSLog(@"%@",OtherMD.front_cover);
        NSLog(@"%@",str);
        
        UIImageView *imageView2 = [[UIImageView alloc]init];
        
  
        [imageView2 sd_setImageWithURL:[NSURL URLWithString:str] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            
            [PlayBtn setImage:imageView2.image forState:UIControlStateNormal];
            
        }];


        [PlayBtn addTarget:self action:@selector(playScreen:) forControlEvents:UIControlEventTouchUpInside];
        
        
        lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 60, kScreenWidth, 1)];
        lineView.backgroundColor = [UIColor grayColor];
        
       UIImageView *PlayView = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenWidth - 59)/2 , (PlayBtn.height - 59)/2, 59, 59)];
        PlayView.image = [UIImage imageNamed:@"bf"];
        
        [PlayBtn addSubview:PlayView];
        [cell.contentView addSubview:PlayBtn];
        [cell.contentView addSubview:lineView];
        [cell.contentView addSubview:imageView];
        [cell.contentView addSubview:VMRnumberLb];
        [cell.contentView addSubview:titleLb];
        [cell.contentView addSubview:useCountLb];
    }
    

    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 240;
}


- (void)playScreen:(UIButton *)btn{
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status == NotReachable) {
        
        
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        HUD.labelText = @"请检查网络连接";
        HUD.mode = MBProgressHUDModeText;
        [HUD hide:YES afterDelay:1.0];
        
        return;
        
    }
    PlayUserModel *otherUserMD = self.UserModelArray[btn.tag];
    PlayModel *otherModel = self.OtherArray[btn.tag];
    
    PlayMoveViewController *playMove = [[PlayMoveViewController alloc]init];
    NSString *playActive_id = [NSString stringWithFormat:@"%@",otherModel.active_id];
    playMove.playStr = playActive_id;
    ;
    
    NSLog(@"%@",playMove.playStr);
    
    
    
    playMove.userID = otherUserMD.userid;
    
    playMove.nameStr = otherUserMD.name;
    playMove.origentionScreen = otherModel.transform;

    [[(MainTabBarController *)KeyWindow.rootViewController selectedViewController]presentViewController:playMove animated:YES completion:nil];
    
    NSLog(@"播放视频");
    
    
}

@end
